<?php
/**
 * 简单的菜品信息处理脚本
 * 用于Windows定时任务执行，避免框架依赖问题
 */

// 添加日志记录功能
function logMessage($message) {
    $logFile = __DIR__ . '/auto_process_dish_info.log';
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[{$timestamp}] {$message}\n", FILE_APPEND | LOCK_EX);
    echo "[{$timestamp}] {$message}\n";
}

// 调用阿里云千问API查询菜品制作信息
function queryDishInfoByQwen($dishes) {
    // 阿里云千问API配置
    $apiKey = 'sk-416b931b781c420c9f6331b7346962b5';
    $apiUrl = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions';
    $model = 'qwen-plus';
    
    // 构造菜品信息列表
    $dishList = "";
    foreach ($dishes as $dish) {
        $dishList .= "ID: {$dish['id']}, 名称: {$dish['name']}\n";
    }
    
    // 构造提示词
    $prompt = "菜品信息列表：\n{$dishList}\n\n请根据这些菜品信息，为每个菜品提供以下信息：\n";
    $prompt .= "1. 所需食材列表（包括食材名称和建议用量）\n";
    $prompt .= "2. 烹饪时长（以分钟为单位）\n";
    $prompt .= "3. 制作步骤（详细步骤）\n\n";
    $prompt .= "请严格按照以下JSON格式返回结果，不要包含其他内容：\n";
    $prompt .= "quantity全部采用g为后缀，没有其他重量方法\n";
    $prompt .= "{\n";
    $prompt .= "  \"菜品ID1\": {\n";
    $prompt .= "    \"ingredients\": [\n";
    $prompt .= "      {\"name\": \"鸡蛋\", \"quantity\": \"150g\"},\n";
    $prompt .= "      {\"name\": \"西红柿\", \"quantity\": \"300g\"}\n";
    $prompt .= "    ],\n";
    $prompt .= "    \"cook_time\": \"7分钟\",\n";
    $prompt .= "    \"steps\": \"1. 热锅凉油...\\n2. ...\"\n";
    $prompt .= "  },\n";
    $prompt .= "  \"菜品ID2\": {\n";
    $prompt .= "    \"ingredients\": [...],\n";
    $prompt .= "    \"cook_time\": \"...\",\n";
    $prompt .= "    \"steps\": \"...\"\n";
    $prompt .= "  }\n";
    $prompt .= "}";
    
    $data = [
        'model' => $model,
        'messages' => [
            [
                'role' => 'user',
                'content' => $prompt
            ]
        ],
        'temperature' => 0.1,
        'max_tokens' => 4000
    ];
    
    logMessage('准备调用千问API: ' . $apiUrl . ', 模型: ' . $model . ', 菜品数量: ' . count($dishes));
    
    // 发起HTTP请求
    $headers = [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json'
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120); // 增加超时到120秒
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); // 增加连接超时到60秒
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    
    logMessage('千问API响应 - HTTP状态码: ' . $httpCode . ', 错误: ' . $error);
    
    if (curl_errno($ch)) {
        $errorMsg = '千问API调用错误: ' . curl_error($ch);
        logMessage($errorMsg);
        curl_close($ch);
        return null;
    }
    
    curl_close($ch);
    
    if ($httpCode !== 200) {
        $errorMsg = '千问API返回错误状态码: ' . $httpCode;
        logMessage($errorMsg);
        return null;
    }
    
    if (empty($response)) {
        $errorMsg = '千问API返回空响应';
        logMessage($errorMsg);
        return null;
    }
    
    $responseArr = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        $errorMsg = '千问API响应JSON解析错误: ' . json_last_error_msg();
        logMessage($errorMsg);
        logMessage('响应内容: ' . $response);
        return null;
    }
    
    if (empty($responseArr['choices'][0]['message']['content'])) {
        $errorMsg = '千问API响应内容为空';
        logMessage($errorMsg);
        logMessage('完整响应: ' . json_encode($responseArr, JSON_UNESCAPED_UNICODE));
        return null;
    }
    
    // 解析返回的JSON内容
    $content = trim($responseArr['choices'][0]['message']['content']);
    logMessage('API返回内容: ' . $content);
    
    // 尝试提取JSON部分
    if (preg_match('/\{.*\}/s', $content, $matches)) {
        $jsonStr = $matches[0];
        $result = json_decode($jsonStr, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            logMessage('成功解析JSON数据');
            return $result;
        } else {
            $errorMsg = '提取的JSON内容解析失败: ' . json_last_error_msg();
            logMessage($errorMsg);
            logMessage('提取的JSON内容: ' . $jsonStr);
        }
    }
    
    logMessage('无法从响应中提取有效的JSON数据');
    return null;
}

// 数据库配置
$config = [
    'hostname' => '127.0.0.1',
    'database' => 'yingyang',
    'username' => 'root',
    'password' => 'root',
    'charset' => 'utf8mb4'
];

try {
    logMessage("开始执行自动处理菜品信息任务");
    
    // 数据库连接
    $dsn = "mysql:host={$config['hostname']};dbname={$config['database']};charset={$config['charset']}";
    $pdo = new PDO($dsn, $config['username'], $config['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // 查询未处理的菜品
    logMessage("查询未处理的菜品");
    $stmt = $pdo->prepare("SELECT id, name FROM fa_food_dish WHERE ai_called = 0 LIMIT 10");
    $stmt->execute();
    $dishes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($dishes)) {
        logMessage("没有需要处理的菜品");
        exit(0);
    }
    
    logMessage("找到 " . count($dishes) . " 个未处理的菜品");
    
    // 调用AI API获取菜品信息
    logMessage("调用AI API获取菜品信息...");
    $aiResult = queryDishInfoByQwen($dishes);
    
    // 处理AI返回的数据，无论成功与否都进行处理
    logMessage("处理菜品信息...");
    foreach ($dishes as $dish) {
        $dishId = $dish['id'];
        $dishName = $dish['name'];
        
        // 默认值
        $cookTime = "模拟烹饪时间 " . rand(5, 60) . "分钟";
        $steps = "模拟制作步骤 1. 准备食材 2. 烹饪 3. 装盘";
        $ingredients = [];
        
        // 如果AI调用成功，使用AI返回的数据
        if (!empty($aiResult)) {
            // 检查AI返回的数据中是否有这个菜品的信息（通过ID查找）
            if (isset($aiResult[$dishId])) {
                $cookTime = $aiResult[$dishId]['cook_time'] ?? $cookTime;
                $steps = $aiResult[$dishId]['steps'] ?? $steps;
                $ingredients = $aiResult[$dishId]['ingredients'] ?? [];
                logMessage("使用AI数据处理: {$dish['name']} (ID: {$dish['id']})");
            }
            // 如果通过ID找不到，尝试通过名称查找（兼容旧格式）
            else if (isset($aiResult[$dishName])) {
                $cookTime = $aiResult[$dishName]['cook_time'] ?? $cookTime;
                $steps = $aiResult[$dishName]['steps'] ?? $steps;
                $ingredients = $aiResult[$dishName]['ingredients'] ?? [];
                logMessage("使用AI数据处理: {$dish['name']} (ID: {$dish['id']})");
            } else {
                logMessage("AI数据中未找到菜品: {$dish['name']} (ID: {$dish['id']})，使用模拟数据");
            }
        } else {
            logMessage("AI调用失败，使用模拟数据处理: {$dish['name']} (ID: {$dish['id']})");
        }
        
        // 开始事务
        $pdo->beginTransaction();
        
        try {
            // 更新菜品状态
            $stmt = $pdo->prepare("UPDATE fa_food_dish SET ai_called = 1, cook_time = ?, steps = ?, updatetime = ? WHERE id = ?");
            $stmt->execute([
                $cookTime,
                $steps,
                time(),
                $dish['id']
            ]);
            
            // 删除原有的食材关联
            $stmt = $pdo->prepare("DELETE FROM fa_food_ingredientrel WHERE dish_id = ?");
            $stmt->execute([$dish['id']]);
            
            // 添加新的食材关联
            if (!empty($ingredients)) {
                $insertStmt = $pdo->prepare("INSERT INTO fa_food_ingredientrel (dish_id, ingredient_name, ingredient_id, parent_id, categories_id, quantity, createtime, updatetime, weigh) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                
                foreach ($ingredients as $index => $ingredient) {
                    // 先保存AI返回的食材名称和用量
                    $ingredientName = $ingredient['name'] ?? '';
                    $quantity = $ingredient['quantity'] ?? '100g';
                    
                    // 查询fa_food_ingredient表，看是否有这个食材
                    $ingredientId = 0;
                    $parentId = null;
                    $categoriesId = null;
                    
                    // 先尝试精确匹配
                    $ingredientStmt = $pdo->prepare("SELECT id, parent_id, categories_id FROM fa_food_ingredient WHERE name = ?");
                    $ingredientStmt->execute([$ingredientName]);
                    $ingredientInfo = $ingredientStmt->fetch(PDO::FETCH_ASSOC);
                    
                    // 如果没有精确匹配，尝试模糊匹配
                    if (!$ingredientInfo) {
                        $ingredientStmt = $pdo->prepare("SELECT id, parent_id, categories_id FROM fa_food_ingredient WHERE name LIKE ?");
                        $ingredientStmt->execute(["%{$ingredientName}%"]);
                        $ingredientInfo = $ingredientStmt->fetch(PDO::FETCH_ASSOC);
                    }
                    
                    // 如果找到了对应的食材，就更新关联信息
                    if ($ingredientInfo) {
                        $ingredientId = $ingredientInfo['id'];
                        $parentId = $ingredientInfo['parent_id'];
                        $categoriesId = $ingredientInfo['categories_id'];
                        logMessage("找到匹配的食材: {$ingredientName}, ID: {$ingredientId}");
                    } else {
                        logMessage("未找到匹配的食材: {$ingredientName}");
                    }
                    
                    // 插入食材关联数据
                    $insertStmt->execute([
                        $dish['id'],
                        $ingredientName,
                        $ingredientId,
                        $parentId,
                        $categoriesId,
                        $quantity,
                        time(),
                        time(),
                        $index + 1
                    ]);
                }
            }
            
            // 提交事务
            $pdo->commit();
            logMessage("处理完成: {$dish['name']} (ID: {$dish['id']}) - 烹饪时间: {$cookTime}");
        } catch (Exception $e) {
            // 回滚事务
            $pdo->rollback();
            logMessage("处理菜品 {$dish['name']} (ID: {$dish['id']}) 失败: " . $e->getMessage());
        }
    }
    
    logMessage("任务执行完成");
    
} catch (Exception $e) {
    $errorMsg = "执行过程中发生错误: " . $e->getMessage();
    $errorFile = "错误文件: " . $e->getFile();
    $errorLine = "错误行号: " . $e->getLine();
    logMessage($errorMsg);
    logMessage($errorFile);
    logMessage($errorLine);
}

logMessage("脚本执行结束");
?>